<template>
  <div style="padding-bottom: 160px;position:relative;">
    <div class="step_box">
      <el-steps :active="active" finish-status="success">
        <el-step title="基础信息"></el-step>
        <el-step title="视频资料"></el-step>
        <el-step title="专属图片"></el-step>
      </el-steps>
    </div>
    
    <!--基础信息-->
    <el-row v-show="active === 0" class="form_box">
      <el-col :span="20">
        <el-form ref="elForm1" :model="formData" size="default" label-width="120px">
          <el-col :span="20">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="formData.productName" placeholder="请输入商品名称" clearable :maxlength="40" show-word-limit :style="{width: '600px'}"></el-input>
            </el-form-item>
            <el-form-item label="生产日期" prop="serveOne">
              <el-input v-model="formData.serveOne" placeholder="请输入生产日期" clearable :style="{width: '260px',marginRight:'40px'}"></el-input>
            </el-form-item>
            <el-form-item label="保质期" prop="serveTwo">
              <el-input v-model="formData.serveTwo" placeholder="请输入保质期" clearable :style="{width: '260px'}"></el-input>
            </el-form-item>
            <el-form-item label="产地" prop="platId">
              <el-input v-model="formData.platId" placeholder="请输入产地" clearable :maxlength="20" show-word-limit :style="{width: '600px'}"></el-input>
            </el-form-item>
            
            <el-form-item label="商品条码" prop="intro">
              <el-input v-model="formData.intro" placeholder="请输入商品条码" clearable :maxlength="40" show-word-limit :style="{width: '600px'}"></el-input>
            </el-form-item>
            <el-form-item label="外包装图片" prop="unitName">
              <div class="sku-img-wrap" :class="{ hide: formData.img!='' }">
                <ImageUpload
                  v-model="formData.intro"
                  :isShowTip="false"
                  :limit="1"
                  listType="picture-card"
                >
                </ImageUpload>
              </div>
            </el-form-item>
          </el-col>
        </el-form>
      </el-col>
    </el-row>
    
    <!--规格信息-->
    <el-row v-show="active === 1" class="form_box">
      <el-col :span="20">
        <el-form-item label="视频地址" prop="unitName">
          <div class="sku-img-wrap" :class="{ hide: formData.img!='' }">
            <FileUpload
              v-model="formData.intro"
              :isShowTip="false"
              :limit="1"
              listType="picture-card"
            >
            </FileUpload>
          </div>
        </el-form-item>
      </el-col>
      
    </el-row>
    <!--规格信息-->
    <el-row v-show="active === 2" class="form_box">
      <el-col :span="20">
        <div class="from-sub-title">专属图片</div>
        <div>
          <ImageUpload
            v-model="imgList"
            :isShowTip="false"
            :limit="10"
            listType="picture-card"
          >
          </ImageUpload>
        </div>
      </el-col>

    </el-row>
    <div class="footer-wrap">
      <el-button size="default" @click="backNext">{{ active===0?'返回':'上一步' }}</el-button>
      <el-button size="default" type="primary" @click="submitForm">{{ active===2?'提交模板':'保存，下一步' }}</el-button>
    </div>
    <SelectCategory :dialogVisible="dialogVisible" :idsList="formData.typeIdList" @onOk="onOk" @onClose="dialogVisible = false"></SelectCategory>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import SelectCategory from '@/components/SelectCategory'
import { getSpecId,saveTemplate,getClassifyList,getTemplateDetail } from "@/api/goods";
import Editor from "@/components/Editor";
import useTagsViewStore from '@/store/modules/tagsView'
import router from '@/router'

const { proxy } = getCurrentInstance();
// 状态管理
const dialogVisible = ref(false)
const specList = ref([])
const id = proxy.$route.query.id
const copyId = proxy.$route.query.copyId
const oneSku = {
  barcode:null,
  img:'',
  outerId:null,
  platId:null,
  skuName:null,
  weight:0,
  specIdList:[],
  wholeName:'无',
  id:null,
}
const skuList = ref([oneSku])
const active = ref(0)
const formData = ref({
  prodType: 1,
  productName: undefined,
  platId:undefined,
  intro: undefined,
  unitName: undefined,
  typeIdList: [],
})
const imgList = ref('')// 商品图片
const detail = ref('')// 富文本
const rules = reactive({
  prodType: [],
  productName: [{
    required: true,
    message: '请输入商品名称',
    trigger: 'blur'
  }],
  serveOne: [{
    required: true,
    message: '请输入服务名称1',
    trigger: 'blur'
  }],
  serveTwo: [{
    required: true,
    message: '请输入服务名称2',
    trigger: 'blur'
  }],
  platId: [{
    required: true,
    message: '请输入吉客云商品ID',
    trigger: 'blur'
  }],
  intro: [],
  unitName: [{
    required: true,
    message: '请输入计量单位',
    trigger: 'blur'
  }],
})

const prodTypeChange = (val)=>{
  formData.value.prodType = val
}

const formData2 = reactive({
  specType: 1
})
if (id || copyId) {
  getTemplateDetail({ id:id || copyId }).then(res => {
    let data =res.data || {}
    formData.value = data
    imgList.value = data.imgList.join(',')
    skuList.value = data.skuList
    specList.value = data.specList
    formData2.specType = data.specType
    detail.value = data.detail
    console.log('specList',specList)
    if(copyId){
      formData.value.id = ''
    }
  })
}

// DOM引用
const elForm1 = ref(null)
const elForm2 = ref(null)

// 生命周期钩子
onMounted(() => {
if (!id && !copyId) {
  addspecList()
}
  // 初始化逻辑
})
// 切换规格
const specTypeChange = (val)=>{
  if(id)return
  console.log(13,val)
  formData2.specType=val
  if(val==1){
    if(skuList.value.length>=1){
      skuList.value = skuList.value.filter((item,i)=>{
        item.wholeName = '无'
        return i==0
      })
    }else if(skuList.value.length<1){
      skuList.value = [oneSku]
    }
  }else{
    skuList.value = []
    // 重新生成sku
    getSkuList(specList.value)
  }
}
// 方法
const submitForm = () => {
  if(active.value==0){
    elForm1.value.validate(valid => {
      if (!valid) return
      // TODO 提交表单
      next()
    })
  }else if(active.value==1){// 第二步
   
    next()
  }else if(active.value==2){
    
    if(imgList.value.length==0){
      proxy.$modal.msgError(`请上传商品图片!`)
      return
    }
    submit()
  }
  
}
const submit = ()=>{
  console.log(1234,imgList.value,detail)
  let skuArr = []// 解析sku
  skuList.value.forEach(item=>{
    skuArr.push(item)
  })
  let params = {
    ...formData.value,
    ...formData2,
    imgList:imgList.value.split(','),
    skuList:skuArr,
    detail:detail.value,
    // typeIdList:[123],// 商品分类id集合
  }
  if(formData2.specType==2){// 多规格才传规格list
    params.specList=specList.value
  }
  if(id){
    params.id = id
  }
  console.log('params',params)
  saveTemplate(params).then(res=>{
    console.log(123,res)
    if(res.code==200){
      proxy.$modal.msgSuccess("保存成功")
      useTagsViewStore().delView(router.currentRoute.value)
      router.go(-1)
    }
  })
}
// 查询参数
const allClassList = ref([])
// 获取所有商品分类
const getAllList = () => {
  const data  = {
    current: 1,
    size: 999,
    type:'1',// 1-商品分类
  }
  getClassifyList(data)
  .then(res => {
    let arr = res.data.records
    allClassList.value = arr
  })
  .finally(() => {
  })
}
getAllList()
const getClassItem = (id)=>{
  let list = allClassList.value
  let currentItem = {}
  list.forEach(item=>{
    if(id == item.id){
      currentItem=item
    }
  })
  return currentItem
}
const resetForm = () => {
  elForm1.value.resetFields()
}
const backNext = () => {
  if(active.value-1<0){
    useTagsViewStore().delView(router.currentRoute.value)
    router.go(-1)
  }
  active.value = active.value-1>0?active.value-1:0
}
const next = () => {
  if (active.value++ > 2) active.value = 0
}

const onOpen = () => {
  dialogVisible.value = true
}

const onOk = (data) => {
  console.log(112, data)
  formData.value.typeIdList = data.value
  dialogVisible.value = false
}

// 添加规格
const addspecList = async () => {
  const newspecList = JSON.parse(JSON.stringify(specList.value))
  let res = await getSpecId()
  console.log(res.data)
  newspecList.push({
    id:res.data,
    specName: '',
    value: '',
    sortNum:newspecList.length+1,
    delFlag:0,
    itemList: []
  })
  specList.value = newspecList
  getSkuList(newspecList)
}

const deletespecList = (idx) => {
  const newspecList = JSON.parse(JSON.stringify(specList.value))
  let arr = newspecList.filter((item,i)=>i!=idx)
  // newspecList.map((item,i)=>{
  //   if(i==idx){
  //     item.delFlag = 1
  //   }
  // })
  specList.value = arr
  getSkuList(arr)
}

// 添加规格值
const addSkuOption = async (index) => {
  const newspecList = JSON.parse(JSON.stringify(specList.value))
  let value = newspecList[index]?.value || ''
  if (!value) {
    proxy.$modal.msgError(`请输入规格值!`)
    return
  }
  let isValFlag = false
  newspecList.forEach(item=>{
    if(item.itemList){
      item.itemList.forEach(item2=>{
        if(item2.specName == value){
          isValFlag=true
        }
      })
    }
  })
  if (isValFlag) {
    proxy.$modal.msgError(`规格值重复!`)
    return
  }
  let res = await getSpecId()
  
  if (newspecList[index]?.itemList) {
    newspecList[index].itemList.push({
      specName:value,
      delFlag:0,
      id:res.data,
      parentId:newspecList[index].id,
    })
  } else {
    newspecList[index].itemList = {
      specName:value,
      delFlag:0,
      id:res.data,
      parentId:newspecList[index].id,
    }
  }
  
  newspecList[index].value = ''
  specList.value = newspecList
  getSkuList(newspecList)
}

// 生成SKU组合
const getSkuList = (attrList) => {
  let skus = []
  const skuMap = new Map()
  
  if (skuList.value) {
    skuList.value.forEach(sku => {
      skuMap.set(sku.spData, sku)
    })
  }
  console.log(111,skuMap)
  attrList.forEach((attr, index) => {
    const attrSku = []
    attr.itemList.forEach(item => {
      console.log(112,item)
      if (!item.specName) {
        return
      }
      if (index === 0) {
        attrSku.push({ [attr.specName]: item.specName })
      } else {
        skus.forEach(it3 => {
          attrSku.push({ ...it3, [attr.specName]: item.specName })
        })
      }
    })
    skus = attrSku
  })
  
  skus.forEach(it => {
    if (it) {
      let objStr = JSON.parse(JSON.stringify(it))
      it.spData = JSON.stringify(it)
      it.specIdList = getSpecItemId(objStr)
      console.log(3,it,objStr)
      let arr = []
      for(let item in objStr){
        arr.push(objStr[item])
      }
      it.wholeName=arr.join(' ')
    }
  })
  
  skus.forEach(it => {
    const sku = skuMap.get(it.spData)
    let data = JSON.parse(it.spData)
    console.log(6,sku,it,data)
    if (sku) {
      it.barcode = sku.barcode
      it.delFlag = sku.delFlag
      it.img = sku.img
      it.outerId = sku.outerId
      it.platId = sku.platId
      it.skuName = sku.skuName
      it.specIdList = sku.specIdList
      it.weight = sku.weight
      it.wholeName = sku.wholeName
      it.id = sku.id
    } else {
      it.barcode = null
      it.delFlag = 0
      it.img = ''
      it.outerId = null
      it.platId = null
      it.skuName = null
      it.weight = 0
      // it.specIdList = sku.specIdList
      // it.wholeName = sku.wholeName
      it.id = null
    }
  })
  console.log(11,skus,attrList,skuMap)
  if(skus.length==0 && attrList.length!=0)return
  skuList.value = skus
}
const getSpecItemId =(it)=>{
  const newspecList = JSON.parse(JSON.stringify(specList.value))
  let arr = []
  let list= []
  for(let item in it){
    arr.push(it[item])
  }
  newspecList.forEach(item=>{
    if(item.itemList){
      item.itemList.forEach(item2=>{
        if(arr.includes(item2.specName)){
          list.push(item2.id)
        }
      })
    }
  })
  return list
}
// 删除规格值
const deleteSkuOption = (i1, i2) => {
  const newspecList = JSON.parse(JSON.stringify(specList.value))
  newspecList[i1].itemList = newspecList[i1].itemList.filter((_, i) => i !== i2)
  specList.value = newspecList
  getSkuList(newspecList)
}

const deleteSku = (idx) => {
  skuList.value = skuList.value.filter((_, i) => i !== idx)
}
//删除分类
const deleteClass = (idx) => {
  let obj = formData.value
  obj.typeIdList = obj.typeIdList.filter((_, i) => i !== idx)
  formData.value = obj
}


const dialogImageUrl = ref('')

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  // dialogVisible.value = true
}
</script>

<style lang="scss" scoped>
// ::v-deep .el-upload--picture-card{
//   width:44px;
//   height:44px;
//   display: flex;
//   justify-content: center;
//   align-items: center;
// }
:deep(.sku-img-wrap) {
  .el-upload--picture-card,.el-upload-list--picture-card .el-upload-list__item-actions,.el-upload-list--picture-card .el-upload-list__item{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 44px;
    height: 44px;
  }
}
:deep(.el-step__title){
    font-size: 14px;
  }
  :deep(.sku-img-wrap .el-upload-list--picture-card .el-upload-list__item-actions span+span){
    margin-left:4px;
  }
  :deep(.sku-img-wrap .el-upload-list__item-actions .el-icon){
  font-size: 14px;
}
:deep(th.platId-column .cell:before) {
    color: var(--el-color-danger);
    content: "*";
    margin-right: 4px;
}
:deep(.hide .el-upload--picture-card) {
    display: none;
}
// el-table_5_column_29 platId-column el-table__cell
.step_box{
  width: 70%;
  margin: 60px auto 0;
  
}
.form_box{
  display: flex;
  justify-content: center;
  padding-top: 38px;
  flex-wrap: wrap;
}
.from-sub-title{
  width:90%;
  padding:2px 0 24px;
  font-size: 16px;
  font-weight: bold;
}
.footer-wrap{
  align-items: center;
    background-color: #fff;
    border-top: 1px solid #e8e8e8;
    bottom: 0;
    box-shadow: 0 -15px 10px -15px #e8e8e8;
    display: flex;
    left: 0;
    min-height: 60px;
    padding: 20px 30px 20px 20px;
    position: fixed;
    width: 100%;
    justify-content: end;
    z-index: 4;
}
.click_a{
  color:#409eff;
}
.product-type{
  border: 1px solid #ccc;
  border-radius: 2px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 10px 20px;
  position: relative;
  text-align: center;
  width: 130px;
  margin-right:10px;
  .main-title {
    color: #000;
    font-size: 14px;
  }
  .sub-title {
    font-size: 12px;
    color:#aaa
  }
  .checked-icon {
    position: absolute;
    bottom: 2px;
    color: #fff;
    right: 2px;
    z-index: 11;
    display:none;
  }
}
.product-type.active{
  background-color: #f6f6fd;
  border: 1px solid #4a89f0;
  .main-title {
    color: #4a89f0;
  }
  .checked-icon {
    display: flex;
    z-index: 12;
  }
}
.product-type.active:after {
    border-bottom: 0 solid #0000;
    border-right: 30px solid #4a89f0;
    border-top: 30px solid #0000;
    bottom: 0;
    content: "";
    display: block;
    position: absolute;
    right: 0;
    z-index: 10;
}
</style>